﻿using System;
using System.Collections.Generic;
using System.Text;

namespace HZY.Services.Sys
{
    using HZY.EFCore;
    using HZY.EFCore.Entitys.Sys;
    using System.Threading.Tasks;
    using System.Linq;

    public class UserService
    {
        public DefaultRepository<Sys_User> db { get; set; }

        public UserService(DefaultRepository<Sys_User> _db) => this.db = _db;

        public async Task<TableViewModel> FindListAsync(int Page, int Rows, Sys_User Search)
        {
            var query = (from users in db.Context.Sys_Users
                         select new
                         {
                             users.User_Name,
                             users.User_LoginName,
                             当前角色 = string.Join("、", from userRoles in db.Context.Sys_UserRoles
                                                     join roles in db.Context.Sys_Roles on userRoles.UserRole_RoleID equals roles.Role_ID
                                                     where userRoles.UserRole_UserID == users.User_ID
                                                     select roles.Role_Name),
                             users.User_Email,
                             users.User_CreateTime,
                             _ukid = users.User_ID
                         });

            query.WhereIF(w => w.User_LoginName == "hzy", !string.IsNullOrWhiteSpace(Search.User_LoginName));

            //query = query.Where(w => false);

            return await db.Context.GetTableViewModel(query, Page, Rows, typeof(Sys_User));
        }

        public async Task<Sys_User> SaveAsync(Sys_User model)
        {
            var rowCount = await db.UpdateByIdAsync(model);

            await db.UnitOfWork.CommitAsync(async () =>
            {
                var existingModel = await db.FindByIdAsync(model.User_ID);

                if (existingModel == null)
                {
                    model = await db.InsertAsync(model);
                }
                else
                {
                    //db.Context.Entry(existingModel).CurrentValues.SetValues(model);
                    //await db.UpdateAsync(model);
                    existingModel = model;
                    await db.UnitOfWork.SaveAsync();
                }

            });

            return model;
        }

        public async Task<int> DeleteAsync(List<Guid> Ids)
        {
            var dels = await db.FindListAsync(w => Ids.Contains((Guid)w.User_ID));
            return await db.DeleteRangeAsync(dels);
        }

        public async Task<Sys_User> FormByIdAsync(Guid Id)
        {
            return await db.FindByIdAsync(Id);
        }









    }
}
